import os
import requests
from lxml import etree


def url_create(anime_id, anime_part):
    return home + "/v/" + str(anime_id) + "-" + str(anime_part) + ".html"


def name_get(id):
    html = etree.parse('http://www.----.---/----/' + str(id) + '.html', etree.HTMLParser())
    return html.xpath('//div[@class="rate r"]/h1/text()')[0]


def url_get(u):
    html = etree.parse(u, etree.HTMLParser())
    url_download = html.xpath('//div[@id="playbox"]/@data-vid')[0][:-4]
    url_list.append(url_download)
    # print(url_download)
    print("\r正在嗅探资源，已找到 %d 个。" % len(url_list), end='')
    url_next = html.xpath('//div[@class = "fav r"]/a[last()]/@href')
    end = html.xpath('//div[@class = "fav r"]/span[last()]/text()')[0]
    if end == "上一集：": return 0
    return url_get(home + url_next[0])


def media_download_m3u8(link, path):

    response = requests.get(link, headers=headers, timeout=20).text
    ts_url = [i for i in response.split() if "#EXT" not in i]
    ts_count = len(ts_url)

    # [print(i) for i in ts_url[:5]]

    file_temp = 0
    for t in range(ts_count):
        print("\r"+str(ts_count)+"/"+str(t+1), end='')
        for i in range(5):
            try:
                file_temp = requests.get(ts_url[t], stream=True)
                with open(path, 'ab') as f:
                    for chunk in file_temp.iter_content(chunk_size=1024 * 1024):
                        if chunk:
                            f.write(chunk)
                file_temp.close()

                # if file_temp.status_code == 200:
                # print(file_temp)
                break
            except Exception as e:
                print("出错了，正在准备重试，第 %d 次" % i+1)
                print(e)


def media_download_mp4(link, file_path):
    file = requests.get(link, stream=True, headers=headers)
    with open(file_path, 'wb') as f:
        for chunk in file:
            if chunk:
                f.write(chunk)
    return 0


def media_dawnload(link, path):
    if link[-1] == "8":return media_download_m3u8(link, path)
    elif link[-1] == "4":return media_download_mp4(link, path)
    else:return print("不标准的文件格式", path, link)


if __name__ == "__main__":
    home = "http://www.----.---"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
    }
    url_list = []
    ID = int(input("请输入要下载的动漫ID："))
    name = name_get(ID)
    print("即将开始下载：", name)
    url = url_create(ID, 1)
    url_get(url)
    count = len(url_list)
    print("\n", name, "共找到", count, "条资源。")
    # [print(i) for i in url_list]
    path = r'D:\动漫'
    os.mkdir(path + '/' + name)
    for item in range(count):
        link = url_list[item]
        print("\n正在下载第 %d 集。" % (item+1))
        file_path = path + '/' + name + '/第 ' + str(item+1) + ' 集.mp4'
        media_dawnload(link, file_path)
